
//
//  CheckerboardView.m
//  Gomoku
//
//  Created by Sekorm on 16/7/25.
//  Copyright © 2016年 HY. All rights reserved.
//

#import "CheckerboardView.h"
#import "UIView+Frame.h"

#define SCREEN_WIDTH [UIScreen mainScreen].bounds.size.width
#define SCREEN_WIDTH_RATIO (SCREEN_WIDTH / 320)  //屏宽比例
static const NSInteger kGridCount = 15;         //多少个格子
static const CGFloat kChessmanSizeRatio = 0.8; //棋子宽高占格子宽高的百分比,大于0,小于1
static const CGFloat kBoardSpace = 20;

typedef enum : NSUInteger {
    GmkHorizontal,
    GmkVertical,
    GmkObliqueDown, //斜向下
    GmkObliqueUp //斜向上
} GmkDirection;

@interface CheckerboardView ()
@property (nonatomic,assign) CGFloat gridWidth;
@property (nonatomic,assign) CGFloat isBlack;
@property (nonatomic,strong) NSMutableArray * sameChessmanArray; //一条线上的同颜色的棋子个数
@property (nonatomic,strong) NSMutableDictionary * chessmanDict; //存放棋子字典的字典
@property (nonatomic,strong) NSString * lastKey; //上一个棋子字典的key值
@property (nonatomic,assign) BOOL  isHighLevel;  //是否是高级棋盘
@property (nonatomic,assign) NSInteger  gridCount;
@property (nonatomic,assign) BOOL  isOver; //游戏是否结束

@end

@implementation CheckerboardView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self setFrame:frame];
    }
    return self;
}

- (void)setFrame:(CGRect)frame{

    CGSize size = frame.size;
    [super setFrame:CGRectMake(frame.origin.x, frame.origin.y, MIN(size.width, size.height), MIN(size.width, size.height))];
}

- (void)layoutSubviews{
    
    [super layoutSubviews];
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        //初始化设置
        [self setUp];
    });
    
}

- (void)setUp{
    
//    self.backgroundColor = [UIColor colorWithRed:200/255.0 green:160/255.0 blue:130/255.0 alpha:1];
    self.backgroundColor = [UIColor lightGrayColor];
    [self drawBackground:self.size];
    [self addGestureRecognizer:[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapBoard:)]];
}

#pragma mark - 绘制棋盘
- (void)drawBackground:(CGSize)size{
    
    self.gridWidth = (size.width - 2 * kBoardSpace) / self.gridCount;
    
    //1.开启图像上下文
    UIGraphicsBeginImageContext(size);
    //2.获取上下文
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    
    CGContextSetLineWidth(ctx, 0.8f);
    //3.1 画16条竖线
    for (int i = 0; i <= self.gridCount; i ++) {
        CGContextMoveToPoint(ctx, kBoardSpace + i * self.gridWidth , kBoardSpace);
        CGContextAddLineToPoint(ctx, kBoardSpace + i * self.gridWidth , kBoardSpace + self.gridCount * self.gridWidth);
    }
    //3.1 画16条横线
    for (int i = 0; i <= self.gridCount; i ++) {
        CGContextMoveToPoint(ctx, kBoardSpace, kBoardSpace  + i * self.gridWidth );
        CGContextAddLineToPoint(ctx, kBoardSpace + self.gridCount * self.gridWidth , kBoardSpace + i * self.gridWidth);
    }
    CGContextStrokePath(ctx);
    
    //4.获取生成的图片
    UIImage *image=UIGraphicsGetImageFromCurrentImageContext();
    //5.显示生成的图片到imageview
    UIImageView * imageView = [[UIImageView alloc]initWithImage:image];
    [self addSubview:imageView];
    UIGraphicsEndImageContext();
}

//点击棋盘,下棋
- (void)tapBoard:(UITapGestureRecognizer *)tap{

    CGPoint point = [tap locationInView:tap.view];
    //计算下子的列号行号
    NSInteger col = (point.x - kBoardSpace + 0.5 * self.gridWidth) / self.gridWidth;
    NSInteger row = (point.y - kBoardSpace + 0.5 * self.gridWidth) / self.gridWidth;
    NSString * key = [NSString stringWithFormat:@"%ld-%ld",col,row];
    if (![self.chessmanDict.allKeys containsObject:key]) {
        UIView * chessman = [self chessman];
        chessman.center = CGPointMake(kBoardSpace + col * self.gridWidth, kBoardSpace + row * self.gridWidth);
        [self addSubview:chessman];
        [self.chessmanDict setValue:chessman forKey:key];
        self.lastKey = key;
        //检查游戏结果
        [self checkResult:col andRow:row andColor:self.isBlack];
        self.isBlack = !self.isBlack;
    }
}

#pragma mark - 私有方法
//检查此时游戏结果
- (void)checkResult:(NSInteger)col andRow:(NSInteger)row andColor:(BOOL)isBlack{
    
    [self checkResult:col andRow:row andColor:isBlack andDirection:GmkHorizontal];
    [self checkResult:col andRow:row andColor:isBlack andDirection:GmkVertical];
    [self checkResult:col andRow:row andColor:isBlack andDirection:GmkObliqueDown];
    [self checkResult:col andRow:row andColor:isBlack andDirection:GmkObliqueUp];
}

 //判断是否大于等于五个同色相连
- (BOOL)checkResult:(NSInteger)col andRow:(NSInteger)row andColor:(BOOL)isBlack andDirection:(GmkDirection)direction{

    if (self.sameChessmanArray.count >= 5) {
        return YES;
    }
    UIButton *currentChessman = self.chessmanDict[[NSString stringWithFormat:@"%ld-%ld",col,row]];
    UIColor * currentChessmanColor = currentChessman.backgroundColor;
    [self.sameChessmanArray addObject:self.chessmanDict[self.lastKey]];
    switch (direction) {
        //水平方向检查结果
        case GmkHorizontal:{
            //向前遍历
            for (NSInteger i = col - 1; i > 0; i --) {
                NSString * key = [NSString stringWithFormat:@"%ld-%ld",i,row];
                UIView * chessman = self.chessmanDict[key];
                if (![self.chessmanDict.allKeys containsObject:key] || chessman.backgroundColor != currentChessmanColor) break;
                [self.sameChessmanArray addObject:self.chessmanDict[key]];
            }
            //向后遍历
            for (NSInteger i = col + 1; i < kGridCount; i ++) {
                NSString * key = [NSString stringWithFormat:@"%ld-%ld",i,row];
                UIView * chessman = self.chessmanDict[key];
                if (![self.chessmanDict.allKeys containsObject:key] || chessman.backgroundColor != currentChessmanColor) break;
                [self.sameChessmanArray addObject:self.chessmanDict[key]];
            }
            if (self.sameChessmanArray.count >= 5) {
                [self alertResult];
                return YES;
            }
            [self.sameChessmanArray removeAllObjects];
            
        }
            break;
        case GmkVertical:{
            //向前遍历
            for (NSInteger i = row - 1; i > 0; i --) {
                NSString * key = [NSString stringWithFormat:@"%ld-%ld",col,i];
                UIView * chessman = self.chessmanDict[key];
                if (![self.chessmanDict.allKeys containsObject:key] || chessman.backgroundColor != currentChessmanColor) break;
                [self.sameChessmanArray addObject:self.chessmanDict[key]];
            }
            //向后遍历
            for (NSInteger i = row + 1; i < kGridCount; i ++) {
                NSString * key = [NSString stringWithFormat:@"%ld-%ld",col,i];
                UIView * chessman = self.chessmanDict[key];
                if (![self.chessmanDict.allKeys containsObject:key] || chessman.backgroundColor != currentChessmanColor) break;
                [self.sameChessmanArray addObject:self.chessmanDict[key]];
            }
            if (self.sameChessmanArray.count >= 5) {
                [self alertResult];
                return YES;
            }
            [self.sameChessmanArray removeAllObjects];
            
        }
            break;
        case GmkObliqueDown:{
            
            //向前遍历
            NSInteger j = col - 1;
            for (NSInteger i = row - 1; i >= 0; i--,j--) {
                NSString * key = [NSString stringWithFormat:@"%ld-%ld",j,i];
                UIView * chessman = self.chessmanDict[key];
                if (![self.chessmanDict.allKeys containsObject:key] || chessman.backgroundColor != currentChessmanColor || j < 0) break;
                [self.sameChessmanArray addObject:self.chessmanDict[key]];
            }
            //向后遍历
            j = col + 1;
            for (NSInteger i = row + 1 ; i < kGridCount; i++,j++) {
                NSString * key = [NSString stringWithFormat:@"%ld-%ld",j,i];
                UIView * chessman = self.chessmanDict[key];
                if (![self.chessmanDict.allKeys containsObject:key] || chessman.backgroundColor != currentChessmanColor || j > kGridCount) break;
                [self.sameChessmanArray addObject:self.chessmanDict[key]];
            }
            if (self.sameChessmanArray.count >= 5) {
                [self alertResult];
                return YES;
            }
            [self.sameChessmanArray removeAllObjects];
            
        
        }
            break;
        case GmkObliqueUp:{
            //向前遍历
            NSInteger j = col + 1;
            for (NSInteger i = row - 1; i >= 0; i--,j++) {
                NSString * key = [NSString stringWithFormat:@"%ld-%ld",j,i];
                UIView * chessman = self.chessmanDict[key];
                if (![self.chessmanDict.allKeys containsObject:key] || chessman.backgroundColor != currentChessmanColor || j > kGridCount) break;
                [self.sameChessmanArray addObject:self.chessmanDict[key]];
            }
            //向后遍历
            j = col - 1;
            for (NSInteger i = row + 1 ; i < kGridCount; i++,j--) {
                NSString * key = [NSString stringWithFormat:@"%ld-%ld",j,i];
                UIView * chessman = self.chessmanDict[key];
                if (![self.chessmanDict.allKeys containsObject:key] || chessman.backgroundColor != currentChessmanColor || j < 0) break;
                [self.sameChessmanArray addObject:self.chessmanDict[key]];
            }
            if (self.sameChessmanArray.count >= 5) {
                [self alertResult];
                return YES;
            }
            [self.sameChessmanArray removeAllObjects];
            
        }
            break;
    }
    return NO;
}

//游戏结果,提示效果
- (void)alertResult{

    self.isOver = YES;
    NSLog(@"self.sameChessmanArray == %ld",self.sameChessmanArray.count);
    for (UIView * view in self.sameChessmanArray) {
        NSString * key = [self.chessmanDict allKeysForObject:view].firstObject;
        NSLog(@"%@",key);
    }
    
    CGFloat width = SCREEN_WIDTH * 0.4 * SCREEN_WIDTH_RATIO;
    UIView * tip = [[UIView alloc]initWithFrame:CGRectMake(0, 0, width, 0.6 * width)];
    tip.backgroundColor = [UIColor colorWithWhite:1 alpha:0.8];
    tip.alpha = 1;
    tip.layer.cornerRadius = 8.0f;
    [self addSubview:tip];
    tip.center = CGPointMake(self.width * 0.5, self.height * 0.5);
    UILabel * label = [[UILabel alloc]init];
    label.text = self.isBlack?@"White win":@"Black win";
    label.numberOfLines = 0;
    [label sizeToFit];
    label.center = CGPointMake(tip.width * 0.5, tip.height * 0.5);
    [tip addSubview:label];
    
    CAKeyframeAnimation * anim = [CAKeyframeAnimation animation];
    anim.values = @[@(1),@(0),@(1)];
    anim.keyPath = @"opacity";
    anim.duration = 2.0f;
    anim.repeatCount = CGFLOAT_MAX;
    for (UIView * view in self.sameChessmanArray) {
        [view.layer addAnimation:anim forKey:@"alpha"];
    }
    
    self.userInteractionEnabled = NO;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [tip removeFromSuperview];
    });
    
    
//    you can cliked the <NewGame> button to start a new game !
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2* NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        if (self.block) {
            self.block();
        }
    });
    
    

}




#pragma mark - 功能方法
- (void)newGame{
    
    self.isOver = NO;
    self.lastKey = nil;
    [self.sameChessmanArray removeAllObjects];
    self.userInteractionEnabled = YES;
    [self.chessmanDict removeAllObjects];
    for (UIView * view in self.subviews) {
        if ([view isKindOfClass:[UIImageView class]]) {
            continue;
        }
        [view removeFromSuperview];
    }
    self.isBlack = NO;
}

//撤回至上一步棋
- (void)backOneStep:(UIButton *)sender{

    if(self.isOver) return;
    
    if (self.lastKey == nil) {
        sender.enabled = NO;
        CGFloat width = SCREEN_WIDTH * 0.4 * SCREEN_WIDTH_RATIO;
        UIView * tip = [[UIView alloc]initWithFrame:CGRectMake(0, 0, width, 0.6 * width)];
        tip.backgroundColor = [UIColor colorWithWhite:1 alpha:0.8];
        tip.layer.cornerRadius = 8.0f;
        [self addSubview:tip];
        tip.center = CGPointMake(self.width * 0.5, self.height * 0.5);
        UILabel * label = [[UILabel alloc]init];
        label.text = self.chessmanDict.count > 0 ? @"只能悔一步棋!!!" : @"请先落子!!!";
        label.font = [UIFont systemFontOfSize:15];
        [label sizeToFit];
        label.center = CGPointMake(tip.width * 0.5, tip.height * 0.5);
        [tip addSubview:label];
        
        self.userInteractionEnabled = NO;
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            self.userInteractionEnabled = YES;
            sender.enabled = YES;
            [tip removeFromSuperview];
            
        });
        return;
    }
    [self.chessmanDict removeObjectForKey:self.lastKey];
    [self.subviews.lastObject removeFromSuperview];
    self.isBlack = !self.isBlack;
    self.lastKey = nil;
}

//改变键盘级别
- (void)changeBoardLevel{
    
    for (UIView * view in self.subviews) {
        [view removeFromSuperview];
    }
    [self newGame];
    self.isHighLevel = !self.isHighLevel;
    [self drawBackground:self.bounds.size];
}


/*手机号码验证*/
+(BOOL)isValidateMobile:(NSString *)mobile
{
    //1开头，11位数字
    NSString *phoneRegex =@"^((13[0-9])|(15[^4,\\D])|(18[0,0-9]))\\d{8}$";//@"^(1)\\d{10}$";//
    NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex];
    return [phoneTest evaluateWithObject:mobile];
}
/** 是否是有效的注册帐号 */
+(BOOL)isValidateUserCount:(NSString *)userCount
{
    NSString *userCountRegex = @"^[0-9]{6,16}$";
    NSPredicate *userCountTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",userCountRegex];
    return [userCountTest evaluateWithObject:userCount];
}
/** 是否是有效的注册昵称，不包含特殊字符 */
+(BOOL)isValidateUserPitName:(NSString *)pitName
{
    NSString *pitNameRegex = @"^[\u4e00-\u9fa5A-Z0-9a-z_-]*$";
    NSPredicate *userPitName = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",pitNameRegex];
    return [userPitName evaluateWithObject:pitName];
}

/** 是否是身份证  */
+ (BOOL)isValidateIDCard:(NSString *)idcard
{
    BOOL flag;
    if (idcard.length <= 0) {
        flag = NO;
        return flag;
    }
    NSString *regex2 = @"^(\\d{14}|\\d{17})(\\d|[xX])$";
    NSPredicate *identityCardPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex2];
    return [identityCardPredicate evaluateWithObject:idcard];
}
/** 是否输入的数字（整数） */
+(BOOL)isNumber:(NSString *)tring
{
    if ([self stringIsNullOrNil:tring]) {
        return NO;
    }
    NSString *regex2 = @"[0-9]{1}$";
    NSPredicate *identityCardPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex2];
    return [identityCardPredicate evaluateWithObject:tring];
}
/** 密码格式是否正确  */
+(BOOL)isPassword:(NSString *)password
{
    NSString *userCountRegex = @"^[0-9a-zA-Z]{6,16}$";
    NSPredicate *userCountTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",userCountRegex];
    return [userCountTest evaluateWithObject:password];
}
/** 支付密码格式是否正确  */
+(BOOL)isPayPassword:(NSString *)password
{
    NSString *userCountRegex = @"^[0-9]{6}$";
    NSPredicate *userCountTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",userCountRegex];
    return [userCountTest evaluateWithObject:password];
}
/** 判断字符串是否为空  */
+(BOOL)stringIsNullOrNil:(NSString *)str
{
    if((NSNull *)str ==[NSNull null] || str ==nil || [@"" isEqualToString:str]){
        return YES;
    }
    //去掉前后空格
    NSString *string = [str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    if (string.length==0) {
        return YES;
    }
    return NO;
}
+(double)getDoubleValueByString:(NSString *)str
{
    NSDecimalNumber *number =[NSDecimalNumber decimalNumberWithString:str];
    double doubleValue = [number doubleValue];//这里一定要用double不能用float或CGFloat，否则序列号精度不准
    
    if (isnan(doubleValue)) {
        return 0;
    }
    return doubleValue;
}
/** 是否为空  */
+(BOOL)isNSnullOrNil:(id)object
{
    
    if((NSNull *)object ==[NSNull null] || object ==nil){
        return YES;
    }
    
    return NO;
}
/** 把字符串转化成int  */
+(NSInteger)stringToInt:(NSString *)str
{
    if(![self stringIsNullOrNil:str]){
        //先转成真正的字符串，原因是可能str表明看是NSString类型，但是真正是int,long隐式类型...
        NSString *string=[NSString stringWithFormat:@"%zd",[str integerValue]];
        return [string integerValue];
    }
    return 0;
}
/** 把字符串转化成int  */
+(CGFloat)stringToCGFloat:(NSString *)str
{
    if(![self stringIsNullOrNil:str]){
        
        NSDecimalNumber *number =[NSDecimalNumber decimalNumberWithString:str];
        double doubleValue = [number doubleValue];
        if (isnan(doubleValue)) {
            return 0.0;
        }
        //这里一定要用double不能用float或CGFloat，否则序列号精度不准
        return doubleValue;
    }
    return 0.0;
}

/** 访问数组 */
+(NSString *)indexOfArr:(NSArray *)arr index:(NSInteger)index
{
    if (arr.count > index) {
        return arr[index];
    }
    return @"";
}

/** 比较两个字符串是否相同  */
+(BOOL)isEqual:(NSString *)str1 str2:(NSString *)str2
{
    if ([self stringIsNullOrNil:str1] || [self stringIsNullOrNil:str2]) {
        return NO;
    }
    if([str2 isEqualToString:str1]){
        return YES;
    }
    
    return NO;
}


/** 根据英文逗号分隔 */
+(NSArray *)spliStringToArr:(NSString *)string
{
    if ([self stringIsNullOrNil:string]) {
        return nil;
    }
    NSArray *arr=[string componentsSeparatedByString:@","];
    return arr;
}
/** 根据数字得到中文数字 */
+(NSString *)getChineseNumByInteger:(NSInteger)num
{
    NSString *numStr=@"";
    switch (num) {
        case 1:
            numStr =@"一";
            break;
        case 2:
            numStr =@"二";
            break;
        case 3:
            numStr =@"三";
            break;
        case 4:
            numStr =@"四";
            break;
        case 5:
            numStr =@"五";
            break;
        case 6:
            numStr =@"六";
            break;
        case 7:
            numStr =@"七";
            break;
        case 8:
            numStr =@"八";
            break;
        case 9:
            numStr =@"九";
            break;
        case 10:
            numStr =@"十";
            break;
        case 11:
            numStr =@"十一";
            break;
        default:
            numStr =[NSString stringWithFormat:@"%zd",num];
            break;
    }
    return numStr;
}
/** 根据数字得到星期几 */
+(NSString *)getChineseNumByWeekInteger:(NSInteger)num
{
    NSString *numStr=@"";
    switch (num) {
        case 0:
            numStr =@"日";
            break;
        case 1:
            numStr =@"一";
            break;
        case 2:
            numStr =@"二";
            break;
        case 3:
            numStr =@"三";
            break;
        case 4:
            numStr =@"四";
            break;
        case 5:
            numStr =@"五";
            break;
        case 6:
            numStr =@"六";
            break;
        case 7:
            numStr =@"日";
            break;
        default:
            numStr =[NSString stringWithFormat:@"%zd",num];
            break;
    }
    return numStr;
}
/** 增加必填的星号 */
+(NSAttributedString *)addStartByStr:(NSString *)str;
{
    NSString *start =@"*";
    NSString *content =[NSString stringWithFormat:@"%@%@",start,str];
    NSMutableAttributedString *attStr =[[NSMutableAttributedString alloc]initWithString:content];
    NSRange range=[content rangeOfString:start];
    [attStr addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:range];
    return attStr;
}
/** 增加非的星号 */
+(NSAttributedString *)addNotStartByStr:(NSString *)str;
{
    NSString *start =@"*";
    NSString *content =[NSString stringWithFormat:@"%@%@",start,str];
    NSMutableAttributedString *attStr =[[NSMutableAttributedString alloc]initWithString:content];
    NSRange range=[content rangeOfString:start];
    [attStr addAttribute:NSForegroundColorAttributeName value:[UIColor whiteColor] range:range];
    return attStr;
}

/**
 🐟新增方法:
 */

//通过富文本实现图文混排:
+ (NSAttributedString *)attrbutedString:(NSString *)text withImage:(UIImage *)image
{
    // 创建可变属性字符串，富文本
    NSMutableAttributedString * attrString = [[NSMutableAttributedString alloc] init];
    // 将UIImage转换为Attachement
    NSTextAttachment * attachment = [[NSTextAttachment alloc] init];
    attachment.image = image;
    // 将Attachement转变为富文本
    NSAttributedString * attachementAttr = [NSAttributedString attributedStringWithAttachment:attachment];
    
    // 将text转变为富文本
    NSAttributedString * textAttr = [[NSAttributedString alloc] initWithString:text attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:14]}];
    
    // 拼接
    [attrString appendAttributedString:textAttr];
    [attrString appendAttributedString:attachementAttr];
    
    return [attrString copy];
}

//通过富文本实现图文混排(可选择方向)
+ (NSAttributedString *)attrbutedString:(NSString *)text withImage:(UIImage *)image pictureIsLeft:(BOOL)IsLeft
{
    
    // 创建可变属性字符串，富文本
    NSMutableAttributedString * attrString = [[NSMutableAttributedString alloc] init];
    // 将UIImage转换为Attachement
    NSTextAttachment * attachment = [[NSTextAttachment alloc] init];
    attachment.image = image;
    //设置图片的偏移:
    attachment.bounds = CGRectMake(0, -2,image.size.width, image.size.height);
    // 将Attachement转变为富文本
    NSAttributedString * attachementAttr = [NSAttributedString attributedStringWithAttachment:attachment];
    
    // 将text转变为富文本
    NSAttributedString * textAttr = [[NSAttributedString alloc] initWithString:text attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:14]}];
    if (IsLeft) {
        [attrString appendAttributedString:attachementAttr];
        [attrString appendAttributedString:textAttr];
    }
    else{
        // 拼接
        [attrString appendAttributedString:textAttr];
        [attrString appendAttributedString:attachementAttr];
    }
    
    return [attrString copy];
}

+(NSAttributedString *)attrbutedString:(NSString *)text withImage:(UIImage *)image textFont:(NSInteger)font pictureIsLeft:(BOOL)IsLeft
{
    // 创建可变属性字符串，富文本
    NSMutableAttributedString * attrString = [[NSMutableAttributedString alloc] init];
    // 将UIImage转换为Attachement
    NSTextAttachment * attachment = [[NSTextAttachment alloc] init];
    attachment.image = image;
    //设置图片的偏移:
    attachment.bounds = CGRectMake(0, -2,image.size.width, image.size.height);
    // 将Attachement转变为富文本
    NSAttributedString * attachementAttr = [NSAttributedString attributedStringWithAttachment:attachment];
    
    // 将text转变为富文本
    if (!text) {
        text = @"";
    }
    NSAttributedString * textAttr = [[NSAttributedString alloc] initWithString:text attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:font]}];
    if (IsLeft) {
        [attrString appendAttributedString:attachementAttr];
        [attrString appendAttributedString:textAttr];
    }
    else{
        // 拼接
        [attrString appendAttributedString:textAttr];
        [attrString appendAttributedString:attachementAttr];
    }
    
    return [attrString copy];
}


/** 获取导航栏下方的黑线*/
+ (UIImageView *)findHairlineImageViewUnder:(UIView *)view
{
    if ([view isKindOfClass:UIImageView.class] && view.bounds.size.height <= 1.0)
    {
        return (UIImageView *)view;
    }
    for (UIView *subview in view.subviews) {
        UIImageView *imageView = [self findHairlineImageViewUnder:subview];
        if (imageView) {
            return imageView;
        }
    }
    return nil;
}



/** 传入一个字符串,分割成时分格式*/
+(NSInteger)spliTimeString:(NSString * )timeString index:(NSInteger)index
{
    NSArray * arr = [timeString componentsSeparatedByString:@":"];
    if (index == 0) {
        return [arr[0] integerValue];
    }
    else{
        return [arr[1] integerValue];
    }
}
//判断内容是否全部为空格  yes 全部为空格  no 不是
+ (BOOL) strIsAllBlankEmpty:(NSString *) str{
    if (!str) {
        return true;
    } else {
        NSCharacterSet *set = [NSCharacterSet whitespaceAndNewlineCharacterSet];
        NSString *trimedString = [str stringByTrimmingCharactersInSet:set];
        if ([trimedString length] == 0) {
            return true;
        } else {
            return false;
        }
    }
}
/**
 *  判断字符串里是不是全是数字
 *
 *  @param string <#string description#>
 *
 *  @return <#return value description#>
 */
+(BOOL)isPureNumandCharacters:(NSString *)string
{
    string = [string stringByTrimmingCharactersInSet:[NSCharacterSet decimalDigitCharacterSet]];
    if(string.length > 0)
    {
        return NO;
    }
    return YES;
}

/**将img变为黑白图片*/
+ (UIImage*) convertImageToGreyScale:(UIImage*) image
{
    CGRect imageRect = CGRectMake(0, 0, image.size.width, image.size.height);
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceGray();
    CGContextRef context = CGBitmapContextCreate(nil, image.size.width, image.size.height, 8, 0, colorSpace, kCGImageAlphaNone);
    CGContextDrawImage(context, imageRect, [image CGImage]);
    CGImageRef imageRef = CGBitmapContextCreateImage(context);
    UIImage *newImage = [UIImage imageWithCGImage:imageRef];
    CGColorSpaceRelease(colorSpace);
    CGContextRelease(context);
    CFRelease(imageRef);
    return newImage;
}

#pragma mark - getter/setter 方法

- (UIView *)chessman{
    UIView * chessmanView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.gridWidth * kChessmanSizeRatio, self.gridWidth * kChessmanSizeRatio)];
    chessmanView.layer.cornerRadius = chessmanView.width * 0.5;
    chessmanView.backgroundColor = !self.isBlack ? [UIColor blackColor]:[UIColor whiteColor];
    return chessmanView;
}

- (NSMutableDictionary *)chessmanDict{
    if (!_chessmanDict) {
        _chessmanDict = [NSMutableDictionary dictionary];
    }
    return _chessmanDict;
}

- (NSMutableArray *)sameChessmanArray{
    if (!_sameChessmanArray) {
        _sameChessmanArray = [NSMutableArray array];
    }
    return _sameChessmanArray;
}

- (NSInteger)gridCount{
    
    return self.isHighLevel ? kGridCount : (kGridCount - 4);
}


@end
